const express = require('express')
const md5 = require("md5")
const verify = require("../middleware/verify")
const loginRouter = express.Router()
const loginVerify = require("../middleware/verify")
// const data = require("../database/user.json")
const infoModel = require("../database/model/info")
const noteModel = require("../database/model/note")

// 注册
loginRouter.post("/register", (req, res) => {
    let { username, pwd } = req.body
    // 判断数据库内是否存在该账号
    infoModel.findOne({username}, (err,data)=>{
        if (!data) {
            // 添加至数据库
            infoModel.create({username,pwd:md5(pwd)}, (err,data) => {
                if (!err) {
                    res.render("jump.html", {ddd:"注册成功" })
                }
            })
        } else {
            res.send("该用户已存在！")
        }
    })

})

// 登录
loginRouter.post("/login", (req, res) => {
    let { username,pwd} = req.body
    infoModel.findOne({username,pwd:md5(pwd)}, (err,data) => {
        if (err) return
        if (data) {
            req.session.username = data.username
            res.render("loginSuccess.html")
        } else {
            res.send("账号或密码错误")
        }
    })

    // let result = data.find(item=>item.username===username&&item.pwd===pwd)
    // if (result) {
    //     req.session.username = result.username
    //     res.render("loginSuccess.html")
    // } else {
    //     res.send("错误")
    // }
})


// 个人中心
loginRouter.get("/center", loginVerify, (req, res) => {
    let username = req.session.username
    // 获取备忘录内容
    noteModel.find({username},(err,data)=>{
        res.render("center.html", {username,data})
    })
})
// 退出登录
loginRouter.get("/logout", loginVerify, (req, res) => {
    req.session.destroy(() => {
        res.render("logoutSuccess.html")
    })
})

module.exports = loginRouter